<script setup>
import { organizeTeamWithInfoAndMember } from "@/api/teamUp";
import { getUsernameById } from "@/api/user";
import { reactive, ref, onMounted, watch } from "vue";
import { SUCCESS } from "@/core/constants/HttpStatus";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store";

/**
 * Step 1
 */

/**基础信息表单 */
const basicInfoRef = ref();
const basicInfoForm = reactive({
  tpTeamName: "", //队伍名
  tpProjectName: "", //比赛名
  tpTeacherNumber: "", //教师人数
  tpNeedStudentNumber: "", //学生人数
  tpRegistrationDeadline: "", //截止日期
  tpContact: "", //联系方式
  tpTeamIntro: "", //队伍简介
  tpAbilityNeed: "", //能力需求
});

/**基础信息表单校验规则 */
const basicInfoRules = {
  tpTeamName: [{ required: true, message: "请输入团队名称", trigger: "blur" }],
  tpProjectName: [
    { required: true, message: "请输入赛事名称", trigger: "blur" },
  ],
  tpRegistrationDeadline: [
    { required: true, message: "请输入截止日期", trigger: "blur" },
  ],
  tpContact: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
  tpTeamIntro: [
    { required: true, message: "请输入队伍简介", trigger: "blur" },
    { min: 10, message: "队伍简介不少于10个字符", trigger: "blur" },
  ],
  tpAbilityNeed: [
    { required: true, message: "请输入能力要求", trigger: "blur" },
    { min: 10, message: "队伍简介不少于10个字符", trigger: "blur" },
  ],
};

//赛事名称部分
//赛事名称列表
const competitionList = [
  "全国大学生统计建模大赛",
  "全国大学生市场调查与分析大赛",
  "“中国软件杯”大学生软件设计大赛",
  "中国高校计算机大赛微信小程序开发大赛",
  "粤港澳大湾区IT应用系统开发大赛",
  "全国高校易班技术创新大会应用研发评比大赛",
  "“泰迪杯”数据分析职业技能大赛",
  "“泰迪杯”数据挖掘挑战赛",
  "中国TRIZ杯大学生创新方法大赛",
  "华南农业大学丁颖杯“发明创意大赛”",
  "全国大学生电子商务“创新、创意及创业”挑战赛",
  "华南农业大学“创客杯”创新创业大赛",
  "中国国际“互联网+”大学生创新创业大赛",
  "“挑战杯”广东大学生创业计划竞赛",
  "数字中国创新大赛",
  "华南农业大学大学生创新创业训练计划项目",
  "华南农业大学大学生暑期“三下乡”社会实践活动",
  "其他",
];
const projectOption = ref(); //下拉框选项
const otherProject = ref(); //其他赛事输入框
function show() {
  if (projectOption.value === "其他") {
    document.getElementById("other").style.display = "block";
  } else {
    document.getElementById("other").style.display = "none";
    basicInfoForm.tpProjectName = projectOption.value;
  }
}
//输入其他比赛名称赋值给tpProjectName
watch(otherProject, (newProject) => {
  basicInfoForm.tpProjectName = newProject;
});
onMounted(() => {
  //隐藏其他赛事输入框
  document.getElementById("other").style.display = "none";
});

//时间选择器  仅不可选择范围（今天之前）
const disabledDate = (time) => {
  return time.getTime() < Date.now();
};

let active = ref(0); //步骤条移动
let steps = ref(1); //表单内容显示
const firstStep = async () => {
  await basicInfoRef.value.validate(async (valid) => {
    if (valid) {
      active.value++;
      steps.value++;
      document.documentElement.scrollTop = 0;
    } else {
      ElMessage.error("信息输入格式有误，请重新检查");
      console.log("表单校验未通过");
    }
  });
};

/**
 * Step 2
 */
//表单选择框内容
const userStore = useUserStore();
const userInfo = userStore.userInfo; //获取用户信息

const options = [
  {
    value: "0",
    label: "指导老师",
  },
  {
    value: "1",
    label: "队伍队长",
  },
  {
    value: "2",
    label: "队伍成员",
  },
];
const isReadOnly = (index) => {
  if (index == 0) {
    return true;
  } else {
    return false;
  }
};

//现有成员表单
const membersFormRef = ref();
const membersForm = reactive({
  info: [{ uid: userInfo.uid, urealname: userInfo.urealname, memberType: "1" }],
});
const memberFormRules = {
  uid: [
    { required: true, message: "请输入学号/工号", trigger: "blur" },
    {
      pattern: /^[0-9]{12}$/,
      message: "学号/工号应为12位正整数",
      trigger: "blur",
    },
  ],
  urealname: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]+$/,
      message: "姓名应该为中文字符",
      trigger: "change",
    },
  ],
  memberType: [{ required: true, message: "请选择成员类型", trigger: "blur" }],
};

// 防抖
const debounce = (func) => {
  let timer = null;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => func && func(args), 800);
  };
};
const addMember = () => {
  let memberItem = {
    uid: "", //学号
    urealname: "", //姓名
    memberType: "", //身份
    queryHandler: debounce(fetchName),
  };
  membersForm.info.push(memberItem);
};

// 自动获取姓名
const fetchName = async ([object, id]) => {
  console.log(id);
  try {
    const res = await getUsernameById(id);
    console.log(res);
    const { code, data, msg } = res.data;
    if (code != SUCCESS) {
      throw new Error(msg);
    }
    object.urealname = data || "";
  } catch (e) {
    ElMessage.error(e?.message || "获取姓名异常");
  }
};
//删除按钮
const removeMember = (index) => {
  membersForm.info.splice(index, 1);
};

//发起招募按钮 发送请求
const organizeTeam = async () => {
  await membersFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let tpTeamIntro = String(basicInfoForm.tpTeamIntro).replaceAll(
          /\n/g,
          "<br />"
        );
        let abilityNeed = String(basicInfoForm.tpAbilityNeed).replaceAll(
          /\n/g,
          "<br />"
        );
        const res = await organizeTeamWithInfoAndMember({
          tpTeamName: basicInfoForm.tpTeamName, //队伍名
          tpProjectName: basicInfoForm.tpProjectName, //比赛名
          tpTeacherNumber: basicInfoForm.tpTeacherNumber, //教师人数
          tpNeedStudentNumber: basicInfoForm.tpNeedStudentNumber, //学生人数
          tpRegistrationDeadline: basicInfoForm.tpRegistrationDeadline, //截止日期
          tpContact: basicInfoForm.tpContact, //联系方式
          tpTeamIntro: tpTeamIntro, //队伍简介
          tpAbilityNeed: abilityNeed, //能力需求
          compositionList: membersForm.info,
        });
        const { code, msg } = res.data;
        console.log(res);
        if (code == SUCCESS) {
          active.value++;
          steps.value++;
          document.documentElement.scrollTop = 0;
        } else {
          throw new Error(msg);
        }
      } catch (e) {
        ElMessage.error(e?.message || "获取姓名异常");
      }
    } else {
      ElMessage.error("信息输入格式有误，请重新检查");
    }
  });
};
</script>
<template>
  <!--组建团队-->
  <div class="team-main">
    <router-link
      class="iconfont icon-guanbi"
      to="/teamUp/teamHub"
    ></router-link>
    <h3 class="title">组建团队</h3>
    <!-- 步骤条 -->
    <div class="steps-tips">
      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="成员添加"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
    </div>
    <!-- 表格填写 -->
    <div v-if="steps == 1">
      <el-form
        ref="basicInfoRef"
        :rules="basicInfoRules"
        :model="basicInfoForm"
      >
        <el-form-item label="团队名称: " class="team-name" prop="tpTeamName">
          <el-input
            v-model="basicInfoForm.tpTeamName"
            style="width: 380px"
          ></el-input>
        </el-form-item>
        <el-row>
          <el-form-item
            label="赛事名称: "
            class="game-name"
            prop="tpProjectName"
          >
            <el-select
              v-model="projectOption"
              class="m-2"
              placeholder="请选择赛事"
              style="width: 380px"
              @change="show"
            >
              <el-option
                v-for="item in competitionList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            id="other"
            style="width: 360px; margin-left: 20px"
            prop="tpProjectName"
          >
            <el-input
              placeholder="请输入比赛名称"
              v-model="otherProject"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-form-item label="团队规模 :" class="member-num">
          <el-form-item label="教师" class="teacher" prop="tpTeacherNumber">
            <el-input-number
              :min="0"
              v-model="basicInfoForm.tpTeacherNumber"
            ></el-input-number
            ><span>&nbsp;&nbsp;名</span>
          </el-form-item>
          <el-form-item
            label="学生总计"
            class="student"
            prop="tpNeedStudentNumber"
          >
            <el-input-number
              :min="1"
              v-model="basicInfoForm.tpNeedStudentNumber"
            ></el-input-number
            ><span>&nbsp;&nbsp;名</span>
          </el-form-item>
        </el-form-item>
        <el-form-item label="截止招募 :" prop="tpRegistrationDeadline">
          <el-date-picker
            type="date"
            :disabledDate="disabledDate"
            v-model="basicInfoForm.tpRegistrationDeadline"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="联系方式 :" prop="tpContact">
          <el-input v-model="basicInfoForm.tpContact"></el-input>
        </el-form-item>

        <el-form-item label="队伍简介 :" prop="tpTeamIntro">
          <el-input
            v-model="basicInfoForm.tpTeamIntro"
            type="textarea"
            :rows="6"
          ></el-input>
        </el-form-item>

        <el-form-item label="能力需求 :" prop="tpAbilityNeed">
          <el-input
            v-model="basicInfoForm.tpAbilityNeed"
            type="textarea"
            :rows="6"
          ></el-input>
        </el-form-item>
        <!-- 控制按钮 -->
        <el-button type="primary" @click="firstStep" class="next-step"
          >下一步</el-button
        >
      </el-form>
    </div>

    <div v-else-if="steps == 2">
      <el-form
        ref="membersFormRef"
        :model="membersForm"
        :rules="memberFormRules"
      >
        <el-row>
          <el-form-item>
            <h4 class="current-member-title">现有成员</h4>
            <i class="iconfont icon-tianjia" @click="addMember"></i
          ></el-form-item>
        </el-row>

        <el-row
          v-for="(member, index) in membersForm.info"
          :key="index"
          :gutter="20"
        >
          <el-col :span="8">
            <el-form-item
              label="学号/工号: "
              :prop="`info[${index}].uid`"
              :rules="memberFormRules.uid"
            >
              <el-input
                v-model="member.uid"
                :disabled="isReadOnly(index)"
                @input="member.queryHandler(member, member.uid)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="姓名: "
              :prop="`info[${index}].urealname`"
              :rules="memberFormRules.urealname"
            >
              <el-input
                v-model="member.urealname"
                :disabled="isReadOnly(index)"
              ></el-input>
            </el-form-item> </el-col
          ><el-col :span="6">
            <el-form-item
              label="身份: "
              :prop="`info[${index}].memberType`"
              :rules="memberFormRules.memberType"
            >
              <el-select v-model="member.memberType">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="isReadOnly(index)"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button
                class="iconfont icon-shanchu"
                @click="removeMember(index)"
                :disabled="isReadOnly(index)"
                >删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="button-row">
          <el-button type="primary" round @click="organizeTeam"
            >发布招募</el-button
          >
        </el-row>
      </el-form>
    </div>

    <div v-else-if="steps == 3" class="finish-msg">
      <i class="finish-icon" disabled>✔</i>
      <p>成功组建队伍并发布招募</p>
    </div>
  </div>
</template>


<style scoped lang="less">
* {
  padding: 0px;
  margin: 0px;
}
.team-main {
  width: 950px;
  margin-top: 30px;
  background-color: white;
  padding: 20px 0px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .icon-guanbi {
    position: relative;
    left: 440px;
    color: gray;
    text-decoration: none;
  }
  .title {
    margin: 10px 0px 30px 0px;
    font-size: 24px;
  }
  .steps-tips {
    width: 80%;
    margin-bottom: 30px;
  }
  .el-form {
    width: 800px;
    .team-name,
    .game-name {
      width: 50%;
      .el-input {
        width: 90%;
      }
    }
    .member-num {
      .teacher,
      .student {
        width: 35%;
        .el-input-number {
          width: 120px;
        }
      }
    }
    .current-member-title {
      font-size: 16px;
      margin-right: 10px;
    }
    .icon-tianjia {
      font-size: 22px;
      color: #409eff;
    }
    .next-step {
      width: 100px;
      margin-left: 42%;
      margin-top: 12px;
    }
    .button-row {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 50px;
      .el-button {
        width: 200px;
      }
    }
  }
  .finish-msg {
    .finish-icon {
      display: block;
      margin-top: 30px;
      width: 250px;
      height: 250px;
      border-radius: 50%;
      font-size: 100px;
      background-color: #67c23a;
      color: white;
      text-align: center;
      line-height: 250px;
    }
    p {
      margin-top: 20px;
      text-align: center;
      font-size: 20px;
      color: #008fff;
    }
  }
}
</style>